using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace SpellCore
{
    public class SimpleFileBasedWordContainer : IWordContainer
    {
        private Hashtable _words;
        private string _filePath;

        public SimpleFileBasedWordContainer(string baseSpellCenterDirectory,  string writingSystemId, string fileName)
        {
            CreateFileIfNeeded(baseSpellCenterDirectory,writingSystemId, fileName);
            _words = new System.Collections.Hashtable();

            using (StreamReader reader = File.OpenText(_filePath))
            {
                string line = reader.ReadLine();
                while (line != null)
                {
                    _words.Add(line, null);
                    line = reader.ReadLine();
                }
                reader.Close();
            }
        }

        private void CreateFileIfNeeded(string baseSpellCenterDirectory, string writingSystemId, string fileName)
        {
            string path = Path.Combine(baseSpellCenterDirectory, writingSystemId);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = System.IO.Path.Combine(path, fileName);
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            _filePath = path;
        }

        public bool Contains(string word)
        {
            return _words.ContainsKey(word);
        }

        public void Add(string word)
        {
            if (!_words.ContainsKey(word))
            {
                _words.Add(word, null);
            }
            Save();
        }

        public void Save()
        {
            using (StreamWriter writer = new StreamWriter(_filePath))
            {
                foreach (string word in _words.Keys)
                {
                    writer.WriteLine(word);
                }
                writer.Close();
            }
        }

        public void Remove(string word)
        {
            if (_words.ContainsKey(word))
            {
                _words.Remove(word);
            }
            Save();
        }

        #region IEnumerator<string> Members

        public string Current
        {
            get { throw new NotImplementedException("The method or operation is not implemented."); }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        #endregion


        public IEnumerable<string> Words
        { 
            get
            {
                foreach (String word in _words.Keys)
                {
                    yield return word;
                }
            } 
        }
    }

}
